<?php
/**
 * created by zzy
 * date: 2017/10/24 9:28
 */

namespace App\Eloquent\Ygt;

use Illuminate\Database\Eloquent\SoftDeletes;
use App\Eloquent\Ygt\Category;

class Process extends DbEloquent{

    use SoftDeletes;
    protected $dates = ['deleted_at'];
    protected $table = 'ygt_process';
    protected static $orderTypeId;

    public function orderType(){
        return $this->belongsTo('App\Eloquent\Ygt\OrderType','ordertype_id');
    }

    // 取一个工序的字段包括字段对应的类型已经下拉的选项等
    public static function getFieldListByProcessId( $processId )
    {
        $process        = self::getInfo( ['id'=>$processId] );
        if( !$process )
        {
            return [];
        }
        $companyId     = $process->company_id;
        $where          = [
            'ygt_process.id'=>$processId, 'a.deleted_at'=>null,'b.company_id'=>$companyId
        ];
        $join           = [
            ['table'=>'ygt_process_field_relation as a', 'field_l'=>'a.process_id', 'field_c'=>'=', 'field_r'=>'ygt_process.id']
        ];
        $fields         = '';
        $fields         .= 'b.field_id as id,b.field_name,b.title,b.field_type,b.text_type,b.category_id,b.children_category_id,b.placeholder,';
        $join[]         = ['table'=>'ygt_process_field_company as b', 'field_l'=>'b.field_id', 'field_c'=>'=', 'field_r'=>'a.field_id'];
        $fields         .= 'a.id as relation_id,a.is_must';
        $lists          = self::getList($where,$fields,'','',['a.orderby','asc'],'',$join);
        $result         = [];
        if( $lists ){
            $listsArr          = $lists->toArray();
            $relationIdArr    = [];
            $fieldTypeArr     = config('process.field_type_select_arr');
            foreach( $listsArr as $key=>$val ){
                $fieldType             = $val['field_type'];
                if( in_array( $fieldType, $fieldTypeArr ) ) {
                    $relationIdArr[]  = $val['relation_id'];
                }
            }
            $result             = [];
            $selectList        = [];
            if( $relationIdArr ){
                $where          = ['relation_id' => ['in',$relationIdArr]];
                $fields         = 'id,pid,relation_id,title,title_type,is_default';
                $select_data    = ProcessFieldRelationSelect::getList($where,$fields,'','',['id','asc'])->toArray();
                foreach( $select_data as $key=>$val ){
                    $valRelationId                    = $val['relation_id'];
                    $selectList[$valRelationId][]    = $val;
                }
            }
            foreach( $listsArr as $key=>$val ){
                $valIsMust          = $val['is_must'];
                $valFieldType       = $val['field_type'];
                $valRelationId      = $val['relation_id'];
                $arr                = $val;
                //材料-材料分类处理
                $categoryObj = new Category();
                if($valFieldType == 4)
                {
                    $tempCategoryIds = '';
                    if(!empty($val['category_id'])){
                        $tempCategoryIds = $val['category_id'];
                    }

                    //$val['children_category_id'] = '8,135';
                    if(!empty($val['children_category_id'])){
                        //子分类的id放到分类id中
                        $tempCategoryIds = $val['children_category_id'];
                    }

                    if(!empty($tempCategoryIds)){
                        //装换分类格式
                        $tempCategoryIdArr = explode(',',$tempCategoryIds);
                        $tempCategoryIdLvlArr_1 = [];
                        $tempCategoryIdLvlArr_2 = [];
                        foreach($tempCategoryIdArr as $category_id){
                            $categoryLvl = $categoryObj->getCategoryLvl($category_id,-1);
                            if($categoryLvl == 1){
                                $tempCategoryIdLvlArr_1[] = $category_id;
                            }
                            else if($categoryLvl == 2){
                                $tempCategoryIdLvlArr_2[] = $category_id;
                            }
                        }
                        $arr['category_id_lvl_1'] = implode(',',$tempCategoryIdLvlArr_1);
                        $arr['category_id_lvl_2'] = implode(',',$tempCategoryIdLvlArr_2);;
                    }
                    else{
                        $arr['category_id_lvl_1'] = '';
                        $arr['category_id_lvl_2'] = '';
                    }

                    if($val['category_id']){
                        $arr['category_id'] = trim($val['category_id'],',');
                    }
                }

                if($valFieldType == 14)
                {
                    $arr['field_type']=11;
                }
                if( $valIsMust == 1 )
                {
                    $arr['placeholder']     = $arr['placeholder'].'(必填)';
                }
                //15'宽*长 16宽*长*高
                $placeholderArr     = [];
                if($valFieldType == 15){
                    $placeholderArr         = explode(',',$arr['placeholder'],2);
                    $placeholderArrCount    = count($placeholderArr);
                    if($placeholderArrCount == 0){
                        $placeholderArr     = ['宽','长'];
                    }else if($placeholderArrCount == 1){
                        $placeholderArr[1]  = '长';
                    }
                    if($arr['placeholder'] == '')
                    {
                        $placeholderArr[0]  = '宽';
                    }
                }else if($valFieldType == 16){
                    $placeholderArr         = explode(',',$arr['placeholder'],3);
                    $placeholderArrCount    = count($placeholderArr);
                    if($placeholderArrCount == 0){
                        $placeholderArr     = ['宽','长','M边'];
                    }else if($placeholderArrCount == 1){
                        $placeholderArr[1]  = '长';
                        $placeholderArr[2]  = 'M边';
                    }else if($placeholderArrCount == 2){
                        $placeholderArr[2]  = 'M边';
                    }
                    if($arr['placeholder'] == '')
                    {
                        $placeholderArr[0]  = '宽';
                    }
                }
                $arr['placeholder_arr'] = $placeholderArr;
                $tempArrData            = $tempArr = [];
                $default_value          = '';
                if( isset($selectList[$valRelationId]) )
                {
                    $tempArrData       = $selectList[$valRelationId];
                    if($valFieldType == 3)
                    {
                        foreach($tempArrData as $k=>$v)
                        {
                            if($v['is_default']==1)
                            {
                                $default_value  = $v['title'];
                            }
                        }
                    }
                }
                $arr['default_value']     = $default_value;
                $tempArr                    = self::setRelationSelectData($tempArrData,$valFieldType);
                $fieldUnit                  = $fieldSelect = [];
                if( $valFieldType == 5 ){
                    $fieldUnit         = $tempArr;
                } else {
                    $fieldSelect       = $tempArr;
                }
                $arr['field_unit']    = $fieldUnit;
                $arr['data']           = $fieldSelect;
                $result[]               = $arr;
            }
        }
        return $result;
    }
    public static function setRelationSelectData($lists, $fieldType=0)
    {
        $result             = [];
        $fieldTypeSelectArr = config('process.field_type_select_arr');//3,5,11,13,14
        $caseValue          = 0;
        if(in_array($fieldType,$fieldTypeSelectArr))
        {
            $caseValue      = 9999;
        }
        if($fieldType == 11) { $caseValue = 11; }
        if($fieldType == 14) { $caseValue = 14; }
        switch ($caseValue)
        {
            case 9999:
                foreach( $lists as $key=>$val )
                {
                    $result[]   = [
                        'id'=>$val['id'], 'title'=>$val['title']
                    ];
                }
                break;
            case 11:
                $listArr        = [];
                foreach( $lists as $key=>$val )
                {
                    $valId              = $val['id'];
                    $valPid             = $val['pid'];
                    $temp               = ['id'=>$valId,'pid'=>$valPid,'title'=>$val['title']];
                    $listArr[$valId]    = $temp;
                }
                foreach( $listArr as $key=>$val )
                {
                    $valPid     = $val['pid'];
                    if($valPid != 0)
                    {
                        $listArr[$valPid]['data'][] = $val;
                        unset($listArr[$key]);
                    }
                }
                foreach($listArr as $key=>$val)
                {
                    $temp       = $val;
                    unset($temp['pid']);
                    if(isset($temp['data']))
                    {
                        foreach($temp['data'] as $k=>$v)
                        {
                            unset($temp['data'][$k]['pid']);
                        }
                    }
                    $result[]   = $temp;
                }
                break;
            case 14:
                $arr14s2        = [];
                foreach( $lists as $key=>$val )
                {
                    if( $val['title_type'] == '14s2' ){
                        $arr14s2[]        = [
                            'id'=>$val['id'], 'title'=>$val['title']
                        ];
                        unset($lists[$key]);
                    }
                }
                foreach( $lists as $key=>$val )
                {
                    $temp            = [
                        'id'=>$val['id'], 'title'=>$val['title'],
                        'data'=>$arr14s2
                    ];
                    $result[]       = $temp;
                }
                break;
            default:
                $result         = [];
        }
        return $result;
    }
    // 只去一个工序的字段 返回值一维数组
    public static function getFieldArrByProcessId( $processId )
    {
        $where          = [
            'ygt_process.id'=>$processId, 'a.deleted_at'=>null
        ];
        $join           = [
            ['table'=>'ygt_process_field_relation as a', 'field_l'=>'a.process_id', 'field_c'=>'=', 'field_r'=>'ygt_process.id'],
            ['table'=>'ygt_process_field as b', 'field_l'=>'b.id', 'field_c'=>'=', 'field_r'=>'a.field_id']
        ];
        $fields         = 'b.field_name';
        $lists          = self::getList($where,$fields,'','',['b.id','desc'],'',$join);
        $result         = [];
        if( $lists ){
            $listsArr  = $lists->toArray();
            foreach( $listsArr as $key=>$val ){
                if($val['field_name'])
                {
                    $result[]       = $val['field_name'];
                }
            }
        }
        return $result;
    }

    public function getProcessListWithStep($orderTypeId){
//        return self::leftJoin('ygt_process_ordertype','ygt_process.id','=','ygt_process_ordertype.process_id')->get();
        return self::leftJoin('ygt_process_ordertype', function ($join) use ($orderTypeId){
            $join->on('ygt_process.id', '=', 'ygt_process_ordertype.process_id')
                ->where([['ygt_process_ordertype.ordertype_id', '=', $orderTypeId]]);
        })->select(['ygt_process.*','ygt_process_ordertype.process_id','ygt_process_ordertype.step_number'])->where('is_last','=','2')->get();
    }
    public function getProcessListByStep($orderTypeId,$stepNumber){
        return self::leftJoin('ygt_process_ordertype', function ($join) use ($orderTypeId,$stepNumber){
            $join->on('ygt_process.id', '=', 'ygt_process_ordertype.process_id')
                ->where([['ygt_process_ordertype.ordertype_id', '=', $orderTypeId],['ygt_process_ordertype.step_number','=',$stepNumber]]);
        })->select(['ygt_process.*','ygt_process_ordertype.process_id','ygt_process_ordertype.step_number'])->where('is_last','=','2')->get();
    }

    //重写方法 20180604 zhuyujun
    public static function getOneValueById( $id, $fileds ){
//        $where              = ['id'=>$id];
//        $result             = self::getOneValue( $where, $fileds );
//        return $result;

        $tmpObj =self::withTrashed()->where(['id'=>$id])->first();
        if($tmpObj){
            if(is_array($fileds)){
                foreach($fileds as $filed){
                    $result[$filed] = $tmpObj->$filed;
                }
            }
            else{
                $result = $tmpObj->$fileds;
            }
        }
        return $result;
    }

}
